﻿#include "displaywidget.h"
#include "ui_displaywidget.h"


DisplayWidget::DisplayWidget(Tree* treedata, QMenu* itemMenu, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DisplayWidget)
{
    ui->setupUi(this);
    menu = itemMenu;
    tree = treedata;
    init();
    initConnections();
}

DisplayWidget::~DisplayWidget()
{
    delete ui;
}

void DisplayWidget::init(){
    QPalette palette = this->palette();
    palette.setBrush(QPalette::Window, QBrush(QColor(250, 250, 250), Qt::SolidPattern));
    this->setAutoFillBackground(true);
    this->setPalette(palette);
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->treeWidget->header()->setStretchLastSection(false);

    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//选择整行
    ui->tableWidget->setGridStyle(Qt::DashLine);//设置格子线
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);//列填充
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(20);//设置默认行高
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//设置单
    ui->tableWidget->setColumnCount(11);
    ui->tableWidget->horizontalHeader()->resizeSection(3, 50);
    ui->tableWidget->horizontalHeader()->resizeSection(5, 110);
    ui->tableWidget->horizontalHeader()->resizeSection(7,110);
    ui->tableWidget->horizontalHeader()->resizeSection(8,110);
    ui->tableWidget->hideColumn(0);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    tableWidgetItemMenu = new QMenu(this);
    relSearch = new QAction("亲戚查询",this);
    detail = new QAction("详情页面", this);
    del = new QAction("删除此项", this);
    tableWidgetItemMenu->addAction(detail);
    tableWidgetItemMenu->addAction(relSearch);
    tableWidgetItemMenu->addAction(del);
}

void DisplayWidget::initConnections(){
    //当添加祖先按钮被按下时，显示添加界面
    connect(ui->AddAncestry, &QPushButton::clicked, this, &DisplayWidget::addAncestry);

    //当表格中的某一行被双击时，显示详情页面
    connect(ui->tableWidget, &QTableWidget::itemDoubleClicked, [this](QTableWidgetItem* temp){
        emit toDetail(ui->tableWidget->item(temp->row(),0)->text().toInt());
    });

    //链接自定义的右键菜单，获取鼠标 位置
    connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, [this](QPoint pos){
        tableWidgetItemMenu->exec(mapToGlobal(pos));
    });

    //自定义右键菜单相关
    //去往详情页
    connect(detail, &QAction::triggered, [this]{
        emit toDetail(ui->tableWidget->item(ui->tableWidget->currentRow(), 0)->text().toInt());
    });
    //去往亲戚查询页
    connect(relSearch, &QAction::triggered, [this]{
        emit toRelSearch(ui->tableWidget->item(ui->tableWidget->currentRow(), 0)->text().toInt());
    });
    //删除此项
    connect(del, &QAction::triggered, [this]{
        deleteValue(ui->tableWidget->item(ui->tableWidget->currentRow(), 0)->text().toInt());
    });
}

int DisplayWidget::currentIndex(){
    return ui->DisplayArea->currentIndex();
}

void DisplayWidget::setCurrentIndex(int index){
    ui->DisplayArea->setCurrentIndex(index);
    if(index == 3||index ==2){
        emit disableMenu();
    }
}

//从家族树中获取数据，并将其显示到表格
void DisplayWidget::inputDataToTableWidget(){
    QStringList header;
    header<<"ID"<<"姓名"<<"出生地"<<"性别"<<"身高"<<"学历"<<"职业"
         <<"出生日期"<<"死亡日期"<<"最高职业"<<"生平简述";
    ui->tableWidget->setHorizontalHeaderLabels(header);

    QList<int> idList = tree->getALLID();
    TreeNode* tmp = nullptr;
    int row = 0;
    ui->tableWidget->setRowCount(idList.size());
    for (int i: idList) {
        tmp = tree->getValueFromID(i);
        addTableWidgetItem(row, tmp);
        row++;
    }
}

//将家族树的树形结构显示出来
void DisplayWidget::inputDataToTreeWidget(){
    QTreeWidgetItem *p, *q;
    p = new QTreeWidgetItem(ui->treeWidget);
    ui->treeWidget->insertTopLevelItem(0, p);
    hashTreeWidgetItem.insert(-1, p);

    TreeInfoItem* treeInfoItemTmp;
    TreeNode* tp;
    TreeNode* tq;
    QQueue<int> fatherIDQueue;

    //祖先特殊处理
    tp = tree->getValueFromID(tree->root);
    treeInfoItemTmp = new TreeInfoItem(menu, ui->treeWidget);
    q = new QTreeWidgetItem(p);
    ui->treeWidget->setItemWidget(q, 0, treeInfoItemTmp);
    hashTreeWidgetItem.insert(tp->ID, q);

    treeInfoItemTmp->setIdM(tp->ID);
    treeInfoItemTmp->setNameM(tp->Name);

    if(tp->PartnerNode!=nullptr){
        hashTreeWidgetItem.insert(tp->PartnerNode->ID, q);
        treeInfoItemTmp->setIdW(tp->PartnerNode->ID);
        treeInfoItemTmp->setNameW(tp->PartnerNode->Name);
    }
    q->setText(0, treeInfoItemTmp->nameM()+treeInfoItemTmp->nameW());

    fatherIDQueue.enqueue(tree->root);

    while (!fatherIDQueue.isEmpty()) {
        int fID = fatherIDQueue.dequeue();
        tq = tree->getValueFromID(fID);

        //循环处理其所有的孩子,并将是父亲的孩子添加到父亲队列中
        for(int id: tq->SonList){
            tp = tree->getValueFromID(id);

            treeInfoItemTmp = new TreeInfoItem(menu, ui->treeWidget);
            q = new QTreeWidgetItem(hashTreeWidgetItem.value(fID));
            ui->treeWidget->setItemWidget(q, 0, treeInfoItemTmp);
            hashTreeWidgetItem.insert(tp->ID, q);

            if(tp->Gender == "男"){
                treeInfoItemTmp->setIdM(tp->ID);
                treeInfoItemTmp->setNameM(tp->Name);
                if(!tp->SonList.isEmpty()){
                    if(tp->PartnerNode!=nullptr){
                        hashTreeWidgetItem.insert(tp->PartnerNode->ID, q);
                        treeInfoItemTmp->setIdW(tp->PartnerNode->ID);
                        treeInfoItemTmp->setNameW(tp->PartnerNode->Name);
                    }
                    fatherIDQueue.enqueue(tp->ID);
                }
            }
            else{
                treeInfoItemTmp->setIdW(tp->ID);
                treeInfoItemTmp->setNameW(tp->Name);
            }
            q->setText(0, treeInfoItemTmp->nameM()+treeInfoItemTmp->nameW());
        }
    }

    setCurrentIndex(0);
    ui->treeWidget->expandToDepth(50);
}

void DisplayWidget::clear(){
    ui->treeWidget->clear();
    ui->tableWidget->clear();
    hashTreeWidgetItem.clear();
    hashTableWidgetItem.clear();
}

//处理当某项添加子女的时候，更新显示
void DisplayWidget::addChild(int treeItemID){
    TreeInfoItem *tp = new TreeInfoItem(menu, ui->treeWidget);

    int ID = tree->getValueFromID(treeItemID)->SonList.last();
    TreeNode* tmp = tree->getValueFromID(ID);
    if(tmp->Gender == "男"){
        tp->setIdM(tmp->ID);
        tp->setNameM(tmp->Name);
    }
    else{
        tp->setIdW(tmp->ID);
        tp->setNameW(tmp->Name);
    }

    QTreeWidgetItem *p = new QTreeWidgetItem(hashTreeWidgetItem.value(treeItemID));
    hashTreeWidgetItem.insert(ID, p);
    p->setText(0, tp->nameM()+tp->nameW());
    ui->treeWidget->setItemWidget(p, 0, tp);

    int row = tree->getALLID().size();
    ui->tableWidget->setRowCount(row);
    addTableWidgetItem(row-1, tmp);

}

//处理当某项添加伴侣的时候，更新显示
void DisplayWidget::addMate(int treeItemID){
    QTreeWidgetItem* p = hashTreeWidgetItem.value(treeItemID);
    TreeInfoItem *tp = static_cast<TreeInfoItem *>(ui->treeWidget->itemWidget(p, 0));
    TreeNode* tmp = tree->getValueFromID(treeItemID)->PartnerNode;

    hashTreeWidgetItem.insert(tmp->ID, p);
    tp->setIdW(tmp->ID);
    tp->setNameW(tmp->Name);
    p->setText(0, tp->nameM()+tp->nameW());

    int row = tree->getALLID().size();
    ui->tableWidget->setRowCount(row);
    addTableWidgetItem(row-1, tmp);
}

//处理某项更新信息的时候，更新显示
void DisplayWidget::updateValue(int treeItemID){
    TreeInfoItem *tp = static_cast<TreeInfoItem *>(ui->treeWidget->itemWidget(hashTreeWidgetItem.value(treeItemID), 0));
    if(tp->getIDM()>0&&tp->getIDW()>0){
        int idM = tp->getIDM();
        int idW = tp->getIDW();
        tp->setNameM(tree->getValueFromID(idM)->Name);
        tp->setNameW(tree->getValueFromID(idW)->Name);
        updateTableWidgetItem(hashTableWidgetItem.value(idM)->row(), tree->getValueFromID(idM));
        updateTableWidgetItem(hashTableWidgetItem.value(idW)->row(), tree->getValueFromID(idW));
    }
    else{
        int ID = tp->getIDM()>0? tp->getIDM():tp->getIDW();
        tp->clear();
        TreeNode* tmp = tree->getValueFromID(ID);
        if(tmp->Gender == "男"){
            tp->setIdW(-2);
            tp->setIdM(ID);
            tp->setNameM(tmp->Name);
        }
        else{
            tp->setIdM(-2);
            tp->setIdW(ID);
            tp->setNameW(tmp->Name);
        }
        updateTableWidgetItem(hashTableWidgetItem.value(ID)->row(), tree->getValueFromID(ID));
    }
}

//处理删除的时候，更新显示
void DisplayWidget::deleteValue(int treeItemID){
    emit closeTool();

    //在执行删除操作前，判断删除的是否为父亲，若是
    //显示删除提示
    if(tree->isFather(treeItemID)){
        QMessageBox *warning = new QMessageBox(QMessageBox::Warning, "提示",
                                               "删除操作会将其伴侣及后代一并删除，"
                                               "请确认是否删除该项",
                                               QMessageBox::Yes | QMessageBox::No, this);
        warning->button(QMessageBox::Yes)->setText("确定");
        warning->button(QMessageBox::No)->setText("取消");
        //如果确认按钮没有按下，退出删除操作
        if(warning->exec()!=QMessageBox::Yes){
            return;
        }
    }

    if(treeItemID == tree->root){
        setCurrentIndex(3);
        clear();
        tree->deleteValue(treeItemID);
        return;
    }

    if(tree->isMother(treeItemID)){
        TreeInfoItem *tp = static_cast<TreeInfoItem *>
                (ui->treeWidget->itemWidget(hashTreeWidgetItem.value(treeItemID), 0));
        tp->clear();
        tp->setNameM(tree->getValueFromID(tp->getIDM())->Name);
        tp->setIdW(-1);
    }
    else{
        hashTreeWidgetItem.value(treeItemID)->parent()->
                removeChild(hashTreeWidgetItem.value(treeItemID));
    }
    QList<int> idList = tree->deleteValue(treeItemID);
    for(int id: idList){
        ui->tableWidget->removeRow(hashTableWidgetItem.value(id)->row());
        hashTableWidgetItem.remove(id);
        hashTreeWidgetItem.remove(id);
    }
    ui->tableWidget->setRowCount(tree->getALLID().size());

}

//添加表格项的函数，参数是表格中的行，和家族树节点
void DisplayWidget::addTableWidgetItem(int row, TreeNode *data){
    QTableWidgetItem* tp;
    tp = new QTableWidgetItem(QString("%1").arg(data->ID));
    tp->setTextAlignment(Qt::AlignCenter);
    hashTableWidgetItem.insert(data->ID, tp);
    ui->tableWidget->setItem(row, 0, tp);

    tp = new QTableWidgetItem(data->Name);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 1, tp);

    tp = new QTableWidgetItem(data->Birthplace);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 2, tp);

    tp = new QTableWidgetItem(data->Gender);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 3, tp);

    tp = new QTableWidgetItem(QString("%1").arg(data->Stature));
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 4, tp);

    tp = new QTableWidgetItem(data->EduBg);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 5, tp);

    tp = new QTableWidgetItem(data->Job);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 6, tp);

    tp = new QTableWidgetItem(data->Birthday);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 7, tp);

    tp = new QTableWidgetItem(data->Deathday);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 8, tp);

    tp = new QTableWidgetItem(data->HighestJob);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 9, tp);

    tp = new QTableWidgetItem(data->LifeTime);
    tp->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 10, tp);
}

//更新表格项的函数
void DisplayWidget::updateTableWidgetItem(int row, TreeNode *data){
    ui->tableWidget->item(row, 1)->setText(data->Name);
    ui->tableWidget->item(row, 2)->setText(data->Birthplace);
    ui->tableWidget->item(row, 3)->setText(data->Gender);
    ui->tableWidget->item(row, 4)->setText(QString("%1").arg(data->Stature));
    ui->tableWidget->item(row, 5)->setText(data->EduBg);
    ui->tableWidget->item(row, 6)->setText(data->Job);
    ui->tableWidget->item(row, 7)->setText(data->Birthday);
    ui->tableWidget->item(row, 8)->setText(data->Deathday);
    ui->tableWidget->item(row, 9)->setText(data->HighestJob);
    ui->tableWidget->item(row, 10)->setText(data->LifeTime);
}

//更新颜色主题的函数
void DisplayWidget::updateTheme(QColor newTheme, QColor oldTheme){
    QString stylesheet = styleSheet();
    stylesheet.replace(oldTheme.name().remove("#"),newTheme.name().remove("#"));
    setStyleSheet(stylesheet);
}
